package cn.edu.java.thread.原子类;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;

import java.util.concurrent.atomic.AtomicReference;

@Data
@AllArgsConstructor
class Person {
    private String name;
}

public class AtomicReferenceDemo {
    @SneakyThrows
    public static void main(String[] args) {
        // 创建初始的Person对象
        Person initialPerson = new Person("Alice");

        // 创建AtomicReference对象并设置初始值
        AtomicReference<Person> atomicReference = new AtomicReference<>(initialPerson);

        // 创建并启动两个线程进行对象引用的更新
        Thread thread1 = new Thread(() -> {
            // 通过循环不断尝试将对象引用更新为"Bob"
            while (!atomicReference.compareAndSet(initialPerson, new Person("Bob"))) {
                // 更新失败，进行其他操作或等待
            }
        });

        Thread thread2 = new Thread(() -> {
            // 通过循环不断尝试将对象引用更新为"Eve"
            while (!atomicReference.compareAndSet(initialPerson, new Person("Eve"))) {
                // 更新失败，进行其他操作或等待
            }
        });

        thread1.start();
        thread2.start();


        Thread.sleep(100);

        // 输出最终的对象引用值
        System.out.println("Final name: " + atomicReference.get().getName());
    }
}

